package org.crmsystem.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.crmsystem.model.Contact;
import org.crmsystem.model.HandleLog;
import org.crmsystem.model.OrgInfo;
import org.crmsystem.model.Pact;
import org.crmsystem.model.Page;
import org.crmsystem.model.Product;
import org.crmsystem.model.Staff;
import org.crmsystem.model.Trade;
import org.crmsystem.service.IContactService;
import org.crmsystem.service.IOrgService;
import org.crmsystem.service.IPactService;
import org.crmsystem.service.IProductService;
import org.crmsystem.service.IStaffService;
import org.crmsystem.service.ITradeService;
import org.crmsystem.util.DateUtil;
import org.crmsystem.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 机构页面控制器
 * @author 郑皓
 *
 */

@Controller
@RequestMapping("/org")
public class OrgController {

	@Autowired
	private IOrgService iOrgService;
	@Autowired
	private IContactService iContactService;
	@Autowired
	private ITradeService iTradeService;
	@Autowired
	private IStaffService iStaffService;
	@Autowired
	private IPactService iPactService;
	@Autowired
	private IProductService iProductService;
	/**
	 * 跳转添加机构页面
	 * @return
	 */
	@RequestMapping("/orgAdd")
	public ModelAndView getIndex() {
		return fourList("orgAdd");
	}
	
	/**
	 * 机构列表页面
	 * @return
	 */
	@RequestMapping("/show")
	public String getIndex1() {
		return "orgList";
	}
	/**
	 * 添加机构action
	 * @param orgInfo
	 * @param trade
	 * @param dateStr
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addOrgAction")
	@ResponseBody
	public String addOrg(OrgInfo orgInfo,Trade trade,String dateStr,String proIdStr) throws Exception{
		orgInfo.setOrgKindId(orgInfo.getOrgKindName()=="省级"?1:2);
		orgInfo.setContactId(Integer.parseInt(orgInfo.getContactName()));
		iOrgService.addOrg(orgInfo);
		if(dateStr!=null){
			trade.setBuyDate(DateUtil.formatDate(dateStr, "YYYY-MM-DD hh:mm:ss"));
		}else{
			trade.setBuyDate(new Date());
		}
		trade.setOrgId(iOrgService.getIdByName(orgInfo.getName()));
		trade.setOperatorId(Integer.parseInt(trade.getOperatorName()));
		trade.setProId(Integer.parseInt(proIdStr));
		iTradeService.addTrade(trade);
		return "";
	}
	/**
	 * 删除机构
	 * @param orgId
	 * @return
	 */
	@RequestMapping("/delOrgAction")
	@ResponseBody
	public String delOrg(String orgId) {
		int id=Integer.parseInt(orgId);
		iOrgService.delOrg(id);
		return "";
	}
	/**
	 * 点击跳转到修改机构
	 * @param orgId
	 * @return
	 */
	@RequestMapping("/updateOrg")
	public ModelAndView updateOrg(String orgId) {
		OrgInfo orgInfo=iOrgService.getOrgById(Integer.parseInt(orgId));
		Trade trade=iTradeService.getTradeByOrgId(Integer.parseInt(orgId));
		if(trade!=null){
			trade.setBuyDateStr(DateUtil.formatDate(trade.getBuyDate(), "YYYY-MM-DD hh:mm:ss"));
		}
		ModelAndView mView=fourList("orgAdd");
		mView.addObject("orgInfo",orgInfo);
		mView.addObject("trade",trade);
		return mView;
	}
	/**
	 * 修改机构信息操作
	 * @param orgInfo
	 * @param trade
	 * @param dateStr
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateOrgAction")
	@ResponseBody
	public String updateOrgAction(OrgInfo orgInfo,Trade trade,String orgIdStr,String dateStr,String tradeIdStr) throws Exception{
		orgInfo.setOrgKindId(Integer.parseInt(orgInfo.getOrgKindName()));
		orgInfo.setId(Integer.parseInt(orgIdStr));
		orgInfo.setContactId(Integer.parseInt(orgInfo.getContactName()));
		iOrgService.updateOrg(orgInfo);
		if (dateStr!="") {
			trade.setBuyDate(DateUtil.formatDate(dateStr, "YYYY-MM-DD hh:mm:ss"));
		}else {
			trade.setBuyDate(new Date());
		}
		trade.setOrgId(Integer.parseInt(orgIdStr));
		if(tradeIdStr!=""){
			trade.setId(Integer.parseInt(tradeIdStr));
		}
		trade.setOperatorId(Integer.parseInt(trade.getOperatorName()));
		iTradeService.updateTrade(trade);
		return "";
	}
	
	/**
	 * 跳转查看详情页面
	 * @param orgId
	 * @return
	 */
	@RequestMapping("/orgDetail")
	public ModelAndView orgDedail(String orgId) {
		OrgInfo orgInfo=iOrgService.getOrgById(Integer.parseInt(orgId));
		Trade trade=iTradeService.getTradeByOrgId(Integer.parseInt(orgId));
	    trade.setBuyDateStr(DateUtil.formatDate(trade.getBuyDate(), "YYYY-MM-DD hh:mm:ss"));
		ModelAndView mView=fourList("orgDetail");
		mView.addObject("orgInfo",orgInfo);
		mView.addObject("trade",trade);
		return mView;
	}
	/**
	 * 根据条件模糊查询
	 * @param search
	 * @param searchText
	 * @return
	 */
	@RequestMapping("/getOListBySearch")
	@ResponseBody
	public HashMap<String, Object> getOListBySearch(String search,String searchText,int currPage,int pageSize) {
		HashMap<String, Object> searchMap=new HashMap<String, Object>();
		searchMap.put("search", search);
		searchMap.put("searchText", searchText);
		searchMap.put("pageSize", pageSize);
		searchMap.put("currPage", currPage);
		ArrayList<OrgInfo> oList=iOrgService.selectOrgList(searchMap);
		HashMap<String, Object> resultMap=new HashMap<String, Object>();
		resultMap.put("total", iOrgService.getOrgCount(searchMap));
		resultMap.put("list", oList);
		return resultMap;
	}
	/**
	 * 封装查询四个list方法
	 * @param pathStr
	 * @return
	 */
	public ModelAndView fourList(String pathStr) {
		ArrayList<Contact> contacts=iContactService.selectContactList(null);
		Map map=new HashMap();
    	map.put("staff", new Staff());
    	map.put("pageSize", 100);
    	map.put("currPage", 1);
        Page page=iStaffService.getStaff(map);
		List staffs=page.getResult();
		List<Pact> pacts= iPactService.findPacts(null);
		List<Product> products=iProductService.select();
		ModelAndView mView=new ModelAndView(pathStr);
		mView.addObject("contactList",contacts);
		mView.addObject("staffList",staffs);
		mView.addObject("pactList",pacts);
		mView.addObject("proList",products);
		return mView;
	}
	/**
     * 导出到EXCEL
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/toExcel")
    public void outExcle(String search,String searchText,HttpServletRequest request, HttpServletResponse response){
        String fileName = "机构信息表";
        HashMap<String, Object> searchMap=new HashMap<String, Object>();
		searchMap.put("search", search);
		searchMap.put("searchText", searchText);
		ArrayList<OrgInfo> oList=iOrgService.selectOrgList(searchMap);
        List<Map<String, Object>> list = outExcelRecord(oList);
        String columnNames[] = { "机构编号", "机构名称", "机构类别", "省份", "城市", "经办人", "联系人"};
        String keys[] = { "id", "name", "orgKindName", "province", "city", "operatorName", "contactName"};
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            try {
                throw e;
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
    /**
     * 记录要导出的所有信息
     *
     * @param projects
     * @return
     */
    private List<Map<String, Object>> outExcelRecord(List<OrgInfo> oList){
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        for (OrgInfo orgInfo : oList) {
			HashMap<String, Object> mapValue=new HashMap<String, Object>();
			mapValue.put("id", orgInfo.getId());
            mapValue.put("name", orgInfo.getName());
            mapValue.put("orgKindName", orgInfo.getOrgKindName());
            mapValue.put("province", orgInfo.getProvince());
            mapValue.put("city", orgInfo.getCity());
            mapValue.put("operatorName", orgInfo.getOperatorNameOrg());
            mapValue.put("contactName", orgInfo.getContactName());
            listmap.add(mapValue);
		}
        return listmap;
    }
}
